//index.js
//获取应用实例
const app = getApp()
var md5 = require("../../utils/md5.js");
Page({
  data: { 
    windowWidth: wx.getSystemInfoSync().windowWidth,
    windowHeight: wx.getSystemInfoSync().windowHeight,
    pixelRatio: wx.getSystemInfoSync().pixelRatio,
    hidden: false,
    setting: false,
    price_total: "0.0",
    lines: {},
    title:'加载中',
    openid:"",
    client:"",
    phone:"",
    order_id:"",
    shop_id: "",
    showModalStatus: false,
    nickName:'',
    avatarUrl:'',
    user_pone:true,
  },

  onLoad: function (option) {
    var scene = decodeURIComponent(option.scene);
    console.log(scene);
    wx.showLoading({
      title: '加载数据',
    })
    
    var that = this;

    wx.login({
      success: function (res_code) {
        console.log(res_code);
     
    if(scene!=undefined && scene!=""){
        var obj_list=scene.split(",")
        console.log(obj_list);
        
        that.setData({
        order_id:obj_list[0],
        client: obj_list[1],
      })
    }else{
      wx.showToast({
        title: "订单不存在",
        icon: 'none',
        duration: 2000
      })
      that.setData({
        order_id: 56,
        client:"mlhb1041.zntech-china.com"
      })
    }
   wx.request({
     url: app.globalData.erpUrl + '/web/get_pos_order',
     data:{
       order_id: that.data.order_id,
       client: that.data.client
     },
     header: {
       "Content-Type": "application/x-www-form-urlencoded"
     },
     success: function (res) {
      //  console.log(res.data);
       wx.setStorageSync('shop_id', res.data.shop_id);
       that.setData({
         price_total: res.data.amount_total,
         title: res.data.shop_name,
         lines: res.data.lines,
         shop_id: res.data.shop_id
       });
        //获取openid
        wx.request({
          url: app.globalData.erpUrl + '/web/get_wx_open_id',
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          data: {
            code: res_code.code,
          },
          success: function (res) {
            wx.setStorageSync("open_id", res.data.openid)
            that.setData({
              xcx_openid: res.data.openid,
            })
            that.CheckXcxOpenid();
            wx.hideLoading();
          }
        })  
          }
        })
      }
    })

  },









  //弹窗动画
  util: function (currentStatu, type_val) {
    console.log(currentStatu);
    console.log(type_val);
    /* 动画部分 */
    // 第1步：创建动画实例   
    var animation = wx.createAnimation({
      duration: 200,  //动画时长  
      timingFunction: "linear", //线性  
      delay: 0  //0则不延迟  
    });

    // 第2步：这个动画实例赋给当前的动画实例  
    this.animation = animation;

    // 第3步：执行第一组动画  
    animation.opacity(0).rotateX(-100).step();

    // 第4步：导出动画对象赋给数据对象储存  
    this.setData({
      animationData: animation.export()
    })

    // 第5步：设置定时器到指定时候后，执行第二组动画  
    setTimeout(function () {
      // 执行第二组动画  
      animation.opacity(1).rotateX(0).step();
      // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象  
      this.setData({
        animationData: animation
      })

      //关闭  
      if (currentStatu == "close") {
        if (type_val == "user_info") {
          this.setData(
            {
              showModalStatus: false
            }
          );
        } else if (type_val == "user_pone") {
          this.setData(
            {
              showModalStatusPhone: false
            }
          );
        }
      }
    }.bind(this), 200)

    // 显示  
    if (currentStatu == "open") {
      if (type_val == "user_info") {
        this.setData(
          {
            showModalStatus: true
          }
        );
      } else if (type_val == "user_pone") {
        this.setData(
          {
            showModalStatusPhone: true
          }
        );
      }
    }
  },

  //获取用户手机号
  getPhoneNumber: function (e) {
    var that = this;
    wx.login({
      success: function (res) {
        //以下开始获取手机号
        var phone = "";
        if (e.detail.errMsg == 'getPhoneNumber:ok') {
          wx.request({
            url: 'https://mylife.zntech-china.com/web/get_wx_phone',
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            data: {
              'encryptedData': e.detail.encryptedData,
              'iv': e.detail.iv,
              'code': res.code
            },
            success: function (res) {
              phone = res.data.phone.phoneNumber
              that.setData({
                phone: phone,
                user_pone: false
              });
              that.CheckXcxOpenidAndTel();
            }
          })
        } else {
          wx.showLoading({
            title: '获取手机号失败',
            icon: 'none'
          })
        }
      }
    })
  },

  /**
 * 验证并且取出用户信息
 */
  CheckXcxOpenid: function () {
    //开始验证注册用户
    var that = this;
    var xcx_openid = that.data.xcx_openid;
    var shop_id = that.data.shop_id;
    var sign = md5.md5('User.CheckXcxOpenid' + shop_id + xcx_openid);
    wx.request({
      url: app.globalData.serviceUrl + 'User.CheckXcxOpenid',
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: {
        sign: sign,
        xcx_openid: xcx_openid,
        shop_id: shop_id
      },
      success: function (res) {
        var result = res.data.data;
        if (result.code == 0) {
          that.setData({
            openid: result.info.openid,
            phone: result.info.reg_tel
          });
        } else {
          that.util('open', 'user_pone');
        }
      }
    })
  },

  /**
  * 验证手机号并且取出用户信息
  */
  CheckXcxOpenidAndTel: function () {
    //开始验证注册用户
    var that = this;
    var reg_tel = that.data.phone;
    var xcx_openid = that.data.xcx_openid;
    var shop_id = that.data.shop_id;
    var sign = md5.md5(reg_tel + 'User.CheckXcxOpenidAndTel' + shop_id + xcx_openid);
    wx.request({
      url: app.globalData.serviceUrl + 'User.CheckXcxOpenidAndTel',
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: {
        sign: sign,
        xcx_openid: xcx_openid,
        shop_id: shop_id,
        reg_tel: reg_tel,
      },
      success: function (res) {
        var result = res.data.data;
        if (result.code == 0) {
          that.setData({
            openid: result.info.openid
          });
          that.util('close', 'user_pone');
        } else {
          that.util('close', 'user_pone');
          that.util('open', 'user_info');
        }
      }
    })
  },

  /**
  * 用户不存在注册新用户
  */
  CheckUserAll: function (e) {
    //开始验证注册用户
    var that = this;
    var avatar = e.detail.userInfo.avatarUrl;
    var nickName = that.replace(e.detail.userInfo.nickName);
    var sex = e.detail.userInfo.gender;
    var reg_tel = that.data.phone;
    var xcx_openid = that.data.xcx_openid;
    var shop_id = that.data.shop_id;
    var sign = md5.md5(avatar + nickName + reg_tel + 'User.CheckUserAll' + sex + shop_id + xcx_openid);
    wx.request({
      url: app.globalData.serviceUrl + 'User.CheckUserAll',
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: {
        sign: sign,
        xcx_openid: xcx_openid,
        shop_id: shop_id,
        reg_tel: reg_tel,
        sex: sex,
        nickName: nickName,
        avatar: avatar,
      },
      success: function (res) {
        var result = res.data.data;
        if (result.code == 0) {
          that.setData({
            openid: result.info.openid
          });
          that.util('close', 'user_info');
        } else {
          that.util('open', 'user_info');
        }
      }
    })
  },

  //过滤emoji表情符号
  replace: function (nickName) {
    return nickName.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, "");
  },






















  getPay:function(){
    var that = this;
    //以下开始支付
    wx.request({
      url: app.globalData.erpUrl + '/web/get_pay_wx',
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: {
        order_id: that.data.order_id,
        client: that.data.client,
        phone: that.data.phone,
        open_id: wx.getStorageSync("open_id")
      },
      success: function (res) {
        console.log(res);
        if (res.data.code == -1) {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          })
        } else if (res.data.code == 500) {
          wx.showModal({
            content: res.data.msg,
          })
        } else {
          console.log("订单支付")
          wx.requestPayment({
            'timeStamp': res.data.data.timeStamp,
            'nonceStr': res.data.data.nonceStr,
            'package': "prepay_id=" + res.data.data.prepayId,
            'signType': 'MD5',
            'paySign': res.data.data.sign,
            'success': function (res) {
              console.log(res);
              console.log(that.data.title);
              wx.redirectTo({
                url: '../result/index?&shop_name=' + that.data.title + '&price=' + that.data.price_total + '&shop_id=' + that.data.shop_id
              })
              return;

            },
            'fail': function (res) {
              console.log(res);
              console.log('取消支付');
              //订单支付取消修改状态
              wx.request({
                url: app.globalData.erpUrl + '/web/fail_pay_wx',
                header: {
                  'Content-Type': 'json'
                },
                data: {
                  client: that.data.client,
                  order_id: that.data.order_id,
                },
                success: function (res) {

                }
              })
            }
          })
        }
      }
    })
  }  
})
